package dao;

import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JOptionPane;

import modelo.Compra_mat;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DaoCompra_mat {
	private static SessionFactory fabrica;

	public DaoCompra_mat() throws Exception {
		fabrica = new Configuration().addClass(modelo.Compra_mat.class).buildSessionFactory();
	}

	public static boolean cadastrarItem(ArrayList<Compra_mat> listaCM) {
		try {
			
			for (Iterator<Compra_mat> iterator = listaCM.iterator(); iterator.hasNext();) {
				Compra_mat item = (Compra_mat) iterator.next();
				
				Session sessao = fabrica.openSession();
				Transaction transacao = sessao.beginTransaction();
				sessao.save(item);
				transacao.commit();
				sessao.flush();
				sessao.close();
				
			}
			
			JOptionPane.showMessageDialog(null, "Salvou os Itens");

			return true;
			
		} catch (Exception ex) {
			return false;
		}
	}

	public void excluir(Compra_mat cm) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();

		sessao.delete(cm);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}

	public void alterar(Compra_mat cm) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();

		sessao.update(cm);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}

	public ArrayList<Compra_mat> consultarTodos() {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		Query q = sessao.createQuery("from modelo.Compra_mat");
		ArrayList<Compra_mat> Items = (ArrayList<Compra_mat>) q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return Items;
	}

	public ArrayList<Compra_mat> consultarCompra(int idcompra) {
	Session sessao = fabrica.openSession();
	Transaction transacao = sessao.beginTransaction();
	Query q = sessao.createQuery("from modelo.Compra_mat where id_compra = " + idcompra);
	ArrayList<Compra_mat> itens = (ArrayList<Compra_mat>) q.list();
	transacao.commit();
	sessao.flush();
	sessao.close();
	return itens;
	}
	

}
